package com.clei.dto;

import com.clei.utils.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 端口占用信息
 *
 * @author Y
 * @date 2024-03-05
 **/
public class PortUse implements PrintData, Comparable<PortUse> {

    /**
     * 协议
     */
    private String protocol;

    /**
     * ip
     */
    private String ip;

    /**
     * port
     */
    private Integer port;

    /**
     * 状态
     */
    private String state;

    /**
     * pid
     */
    private String pid;

    /**
     * process
     */
    private String process;

    /**
     * title
     *
     * @return list
     */
    public static List<String> getTitle() {
        return Arrays.stream(new String[]{"协议", "IP", "PORT", "状态", "PID", "PROCESS"}).collect(Collectors.toList());
    }

    public PortUse() {
    }

    public PortUse(String protocol, String ip, Integer port, String state, String pid) {
        this.protocol = protocol;
        this.ip = ip;
        this.port = port;
        this.state = state;
        this.pid = pid;
    }

    /**
     * toListString
     *
     * @return list
     */
    @Override
    public List<String> toListString() {
        return Arrays.stream(new String[]{protocol, ip, String.valueOf(port), state, pid, process}).collect(Collectors.toList());
    }

    public String getProtocol() {
        return protocol;
    }

    public String getIp() {
        return ip;
    }

    public Integer getPort() {
        return port;
    }

    public String getState() {
        return state;
    }

    public String getPid() {
        return pid;
    }

    public String getProcess() {
        return process;
    }

    public void setProcess(String process) {
        this.process = process;
    }

    @Override
    public int compareTo(@NotNull PortUse o) {
        // 优先监听状态的
        String listening = "LISTENING";
        boolean aEquals = listening.equals(this.getState());
        boolean bEquals = listening.equals(o.getState());
        int res = 0;
        if (aEquals) {
            if (!bEquals) {
                res = -1;
            }
        } else {
            if (bEquals) {
                res = 1;
            } else {
                res = this.getState().compareTo(o.getState());
            }
        }
        if (0 != res) {
            return res;
        }
        // ip
        res = this.getIp().compareTo(o.getIp());
        if (0 != res) {
            return res;
        }
        // PID
        int aPid = StringUtil.isBlank(this.getPid()) ? 0 : Integer.parseInt(this.getPid());
        int bPid = StringUtil.isBlank(o.getPid()) ? 0 : Integer.parseInt(o.getPid());
        return aPid - bPid;
    }
}
